package cn.passlink.www.ServerImpl;

import cn.passlink.www.Enity.Article;
import cn.passlink.www.Enity.Comment;
import cn.passlink.www.Enity.sysUser;
import cn.passlink.www.Mapper.ArticleDao;
import cn.passlink.www.Mapper.CommentDao;
import cn.passlink.www.Mapper.sysUserDao;
import cn.passlink.www.Server.CommentServer;
import cn.passlink.www.Utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Service
@Slf4j
public class CommentServerImpl implements CommentServer {

    @Autowired
    private CommentDao commentDao;

    @Autowired
    private sysUserDao sysUserDao;

    @Autowired
    private ArticleDao ArticleDao;


    /**
     * getList
     * 获取评论
     * <p>
     * 获取主评论:
     * 从comments_article 找出所有主评论id
     * 从comments_user找出评论者id，根据id找出名字
     * 根据id获取全部comments,构建主评论
     * <p>
     * 获取从评论:
     * 从main_follow_com找出所有从评论id
     * 从comments_user找出评论者id，根据id找出名字
     * 根据id获取全部comments,构建从评论
     *
     * @param article_id
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/15
     **/

    @Override
    public Map<String, Object> getList(String article_id) {

        try {
            Article article = ArticleDao.findById(article_id);
            if (article == null) {
                log.info("文章不存在");
                return JsonUtils.resultJson(200, "文章不存在");
            }
            List<Comment> list = commentDao.getCommentsByArticleId(article_id);
            List<Map<String, Object>> resultList = new ArrayList<>();

            for (Comment comment : list) {
                Map<String, Object> mainComment = buildCommentMap(comment);
                if (mainComment == null) {
                    continue;
                }

                List<Comment> followList = commentDao.findCommentFollowIds(comment.getComment_id());
                List<Map<String, Object>> followComments = buildFollowComments(followList);

                mainComment.put("follow_comments", followComments);
                resultList.add(mainComment);
            }
            int comments_size = ArticleDao.getCommentsCounts(article_id);
            Collections.reverse(resultList);
            return JsonUtils.dataListJson(200, resultList, "获取成功", comments_size);
        } catch (Exception e) {
            log.info("评论获取失败",e);
            return JsonUtils.resultJson(500, "获取失败");
        }
    }

    /**
     * buildCommentMap
     * 主评论
     *
     * @param comment
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/11/10
     **/

    private Map<String, Object> buildCommentMap(Comment comment) {
        try {
            //此处只寻找第一位
            sysUser user = commentDao.findUserById(comment.getComment_id());
            if (user == null) {
                log.error("用户获取失败");
                return null;
            }

            Map<String, Object> mainComment = new HashMap<>();
            mainComment.put("comment_id", comment.getComment_id());
            mainComment.put("avatar", user.getAvatar());
            mainComment.put("nickname", user.getNickname());
            mainComment.put("content", comment.getContent());
            mainComment.put("create_time", comment.getCreate_time());

            return mainComment;
        } catch (Exception e) {
            log.error("构建主评论信息失败",e);
            return null;
        }
    }

    /**
     * buildFollowComments
     * 从评论构建
     *
     * @param followList
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author passlink
     * @create 2023/11/10
     **/

    private List<Map<String, Object>> buildFollowComments(List<Comment> followList) {
        List<Map<String, Object>> followComments = new ArrayList<>();
        for (Comment followComment : followList) {
            try {
                sysUser userFollow = commentDao.findUserById(followComment.getComment_id());
                if (userFollow == null) {
                    continue;
                }
                Map<String, Object> singleFollowComment = new HashMap<>();
                singleFollowComment.put("comment_id", followComment.getComment_id());
                singleFollowComment.put("avatar", userFollow.getAvatar());
                singleFollowComment.put("nickname", userFollow.getNickname());
                singleFollowComment.put("content", followComment.getContent());
                singleFollowComment.put("create_time", followComment.getCreate_time());

                followComments.add(singleFollowComment);
            } catch (Exception e) {
                log.error("构建跟帖评论信息失败",e);
               return  null;
            }
        }
        Collections.reverse(followComments);
        return followComments;
    }

    /**
     * pullCom
     * 上传评论，
     * 主评论与文章关系存入comments_article，
     * 主评论与从评论关系存入main_follow_com,
     * 评论人与评论关系存入comments_user
     * 全部评论放入comments
     *
     * @param user_id
     * @param article_id
     * @param comment_id
     * @param content
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author passlink
     * @create 2023/10/15
     **/

    @Override
    public Map<String, Object> pullCom(String user_id, String article_id, String comment_id, String content, String isMain) {
        String formattedDate = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setCreate_time(formattedDate);
        //创建uid
        try {
            //检查数目
            int comments_size = ArticleDao.getCommentsCounts(article_id);
            if (comments_size > 100) {
                log.error(article_id+"评论数量已经达到上限500");
                return JsonUtils.resultJson(500, "评论数量已经达到上限，无法进行评论！！！");
            }
            Article article = ArticleDao.findById(article_id);
            if (article == null) {
                log.error("文章不存在");
                return JsonUtils.resultJson(403, "评论失败");
            }
            comment.setComment_id(generateUniqueId());
        } catch (NoSuchAlgorithmException e) {
            log.error("评论失败", e);
            return JsonUtils.resultJson(500, "评论失败");
        }

        //先判断是否为主评论
        if (isMain.equals("1") || comment_id.isEmpty()) {
            try {
                comment.setIs_main(1);
                //主评论与文章关系存入comments_article
                commentDao.pullArticleCommentId(comment.getComment_id(), article_id);
//                评论人与评论关系存入comments_user
                commentDao.pullUserCommentId(comment.getComment_id(), user_id);
//                 评论放入comments
                commentDao.insertComment(comment);

                //更新评论大小
                ArticleDao.updateCommentsCounts(article_id);
                return JsonUtils.resultJson(200, "评论成功！！！");
            } catch (Exception e) {
                log.error("主评论---失败",e);
                return JsonUtils.resultJson(500, "评论失败");
            }

        }

        //从评论 处理
        try {
            comment.setIs_main(0);
            //检查该文章id与主评论是否存在关系
            String articleId = commentDao.getArticleIdByCommentId(comment_id);
            if (articleId.isEmpty() || !articleId.equals(article_id)) {
                log.error("评论失败,评论对象错误");
                return JsonUtils.resultJson(403, "评论失败！！！");
            }
//       主评论与从评论关系存入main_follow_com,
            commentDao.pullMainFollow(comment_id, comment.getComment_id());
            //                评论人与评论关系存入comments_user
            commentDao.pullUserCommentId(comment.getComment_id(), user_id);
//                 评论放入comments
            commentDao.insertComment(comment);
            //更新评论大小
            ArticleDao.updateCommentsCounts(article_id);
            return JsonUtils.resultJson(200, "评论成功！！！");
        } catch (Exception e) {
            log.error("从评论---失败",e);
            return JsonUtils.resultJson(500, "评论失败!!!");
        }

    }

    /**
     * generateUniqueId
     * 生产id
     *
     * @return java.lang.String
     * @author passlink
     * @create 2023/10/14
     **/
    public String generateUniqueId() throws NoSuchAlgorithmException {
        long timestamp = new Date().getTime();
        String stringToHash = Long.toString(timestamp);
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] hashBytes = messageDigest.digest(stringToHash.getBytes());
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : hashBytes) {
            stringBuilder.append(String.format("%02x", b));
        }
        return stringBuilder.substring(0, 16);
    }
}
